package com.xiezc.service;

import com.xiezc.entity.FileInfo;
import lombok.Data;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Data
public class SaveFileCallBack implements Callback<ResponseBody> {

    private FileInfo fileInfo;

    private String rootPath;

    public SaveFileCallBack(FileInfo fileInfo) {
        this.fileInfo = fileInfo;
    }

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            Path path = Paths.get(rootPath + "\\" + fileInfo.getFilePath() + "\\" + fileInfo.getFileName());
            try {
                if (Files.exists(path.getParent())) {
                    Files.createDirectories(path.getParent());
                }
                if (Files.exists(path)) {
                    Files.createFile(path);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            try (
                    BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(path));
                    BufferedInputStream bis = new BufferedInputStream(responseBody.byteStream());
            ) {
                byte[] b = new byte[2048];
                int len = 0;
                while ((len = bis.read(b)) > 0) {
                    bos.write(b, 0, len);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {

        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {

    }
}
